<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-card-box">
                <div class="layui-btn-group">
                    <a class="layui-btn" id="menus-add" v-show="@admin/menu/add"><i class="layui-icon layui-icon-add-circle"></i> 添加</a>
                    <!--<a class="layui-btn" id="menus-del" v-show="@admin/menu/del"><i class="layui-icon layui-icon-delete"></i> 删除</a>-->
                    <a class="layui-btn" id="menus-sz" data="1"><i class="layui-icon">&#xe624;</i>展开</a>
                </div>
            </div>
            <table lay-filter="menus" id="menus"></table>
        </div>
    </div>
</div>
<!--JS部分-->
<script>
    layui.use(['trTable','iconPicker','buildItems'],function(){
        var map_root = layui.cache.maps;
        var app_root = map_root + 'admin/menu/';
        var layer = layui.layer,form = layui.form,admin = layui.admin,treeTable = layui.trTable;

        /* 渲染表格 https://gitee.com/whvse/treetable-lay  https://gitee.com/whvse/treetable-lay/wikis/pages */
        var menusTb = treeTable.render({
            elem: '#menus',
            checkdd: false,
            url: app_root+"index?do=json",
            toolbar: [
                '<p><span class="layui-inline"><input class="layui-input" id="edtSearch" placeholder="输入关键字" style="width:140px;margin-right:5px;height:30px;"></span>',
                '<button id="btnSearch" class="layui-btn layui-btn-sm layui-btn-primary layui-inline"><i class="layui-icon"></i>搜索</button>',
                '<button id="btnClearSearch" class="layui-btn layui-btn-sm layui-btn-primary layui-inline"><i class="layui-icon"></i>清除搜索</button></p>'
            ].join(''),
            tree: {
                iconIndex: 2,
                isPidData: true,
                idName: 'id',
                pidName: 'pid',
                arrowType: 'arrow2',
                getIcon: 'v-tree-icon-style2'
            },
            cols: [[
                {type:'checkbox',fixed:'left'},
                {field:'id',width:50,unresize:true,align:'center',title:'ID'},
                {field:'name',minWidth:150,edit:'text',title:'名称'},
                {field:'url',minWidth:150,edit:'text',title:'菜单标识'},
                {field:'act',minWidth:150,edit:'text',title:'权限路径'},
                {field:'link',minWidth:150,edit:'text',title:'外链路径'},
                {field:'icon',width:50,align:'center',templet:function(d){return d.icon ? '<i class="layui-icon '+ d.icon +'"></i>' : '';},title:'图标'},
                {field:'sort',width:50,edit:'text',align:'center',title:'排序'},
                {field:'is_menu',width:60,align:'center',templet:function(d){return '<input type="checkbox" name="is_menu" lay-skin="switch" lay-text="是|否" lay-filter="menus-chang" value="'+d.is_menu+'" data-json="'+encodeURIComponent(JSON.stringify(d))+'"'+(d.is_menu===1 ? ' checked' : '')+'>';},unresize:true,title:'菜单'},
                {field:'status',width:60,align:'center',templet:function(d){return '<input type="checkbox" name="status" lay-skin="switch" lay-text="是|否" lay-filter="menus-chang" value="'+d.status+'" data-json="'+encodeURIComponent(JSON.stringify(d))+'"'+(d.status===1 ? ' checked' : '')+'>';},unresize:true,title:'显示'},
                {fixed:'right',width:150,align:'center',toolbar:'<div><a class="layui-btn layui-btn-xs" lay-event="adds">添加</a><a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="edit">编辑</a><a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a></div>',title:'操作'}
            ]]
        });

        /*顶部-添加按钮*/
        $('#menus-add').on('click',function(){addOpen();});
        /*顶部-删除按钮*/
        $('#menus-del').on('click', function(){
            var checkRows = menusTb.checkStatus();
            if(checkRows.length === 0){return layer.msg('请选择需删除的菜单');}
            var ids = checkRows.map(function(d){return d.id;});
            del(ids);
        });
        /*顶部-展开或折叠*/
        $('#menus-sz').click(function(){
            var ob = $(this),i,t;
            if(ob.attr('data') == 1){
                menusTb.expandAll();
                i=0;t='<i class="layui-icon">&#xe67e;</i>折叠';
            }else{
                menusTb.foldAll();
                i=1;t='<i class="layui-icon">&#xe624;</i>展开';
            }
            ob.attr('data',i).html(t);
        });

        /*搜索、清除搜索*/
        $('#btnSearch').click(function(){
            var keywords = $('#edtSearch').val();
            if(keywords){
                menusTb.clearFilter();
                menusTb.filterData(keywords);
            }else{
                menusTb.clearFilter();
            }
        });
        $('#btnClearSearch').click(function(){menusTb.clearFilter();});

        /*列表-是否菜单、菜单显示*/
        form.on('switch(menus-chang)',function(obj){
            var json = JSON.parse(decodeURIComponent($(this).data('json')));
            var av = obj.elem.checked ? 1 : 0;
            admin.req(app_root+"edit?do=switch",{id:json.id,av:av,af:obj.elem.name},function(res){
                layer.tips(res.msg,obj.othis,{time:1000});
                if(res.code === 0) obj.elem.checked = parseInt(obj.value);
            },'post',{headersToken:true});
        });
        /*列表-列表内快编监听*/
        treeTable.on('edit(menus)',function(obj){
            admin.req(app_root+"edit?do=fast",{id:obj.data.id,av:obj.value,af:obj.field},function(res){
                layer.msg(res.msg,{shade:[0.4,'#000'],time:1000});
            },'post',{headersToken:true});
        });
        /*列表-操作-工具条监听*/
        treeTable.on('tool(menus)', function(obj){
            var data = obj.data;
            if(obj.event === 'adds'){
                addsOpen(data.id);
            }else if(obj.event === 'edit'){
                addOpen(data);
            }else if(obj.event === 'del'){
                del(data.id);
            }
        });

        /*删除*/
        function del(ids){
            layer.confirm('确定要删除所选菜单吗？', function(){
                admin.req(app_root+"del",{id:ids},function(res){
                    layer.msg(res.msg,{shade:[0.4,'#000'],time:1500},function(){
                        if(res.code===1) menusTb.refresh();
                    });
                },'post',{headersToken:true});
            });
        }

        /*批量添加*/
        function addsOpen(id){
            admin.open({
                type: 1,
                bid: 'menuss_items',
                btn: ['确认添加', '取消'],
                area: ['460px', '350px'],
                title: '批量添加菜单',
                success: function(l,index){
                    l.children('.layui-layer-content').css('overflow', 'visible');
                    layui.buildItems.build({
                        bid: 'menuss_items',
                        data: [
                            {name:"pid",title:"上级ID",type:"number",value:id,verify:'required',placeholder:"请输入上级ID，0：为顶级",must:true},
                            {name:"name",title:"菜单名称",type:"textarea",value:'',verify:'required',style:"height:160px",placeholder:"可批量添加，一行一个，点回车换行",must:true}
                        ]
                    });
                    form.on('submit(menuss_items)',function(data){
                        var btn = $(this);
                        if (btn.attr('stop')){return false}else{btn.attr('stop',1)}
                        admin.req(app_root+"add?do=batch",data.field,function(res){
                            layer.msg(res.msg,{shade:[0.4,'#000'],time:1500},function(){
                                if(res.code===1){
                                    layer.close(index);
                                    menusTb.refresh();
                                    $('#menus-sz').trigger('click');
                                }
                                btn.removeAttr('stop');
                            });
                        },'post',{headersToken:true});
                        return false;
                    });
                }
            });
        }

        /*添加、编辑弹出窗*/
        function addOpen(Dt){
            admin.open({
                type: 1,
                bid: 'menus_items',
                btn: ['保存', '取消'],
                area: ['660px', '90%'],
                title: (Dt ? '编辑' : '添加') + '菜单',
                success: function(lay,index){
                    layui.buildItems.build({
                        bid: 'menus_items',
                        data: [
                            {name:"id",type:"hidden"},
                            {name:"pid",title:"上级菜单",type:"html",html:'<div v-dict="MPARENTID" options="{name:\'pid\',prop:{name:\'name\',value:\'id\'},initValue:['+(Dt ? Dt.pid : 0)+']}" class="v-xmselect-tree"></div>',must:true},
                            {name:"name",title:"菜单名称",type:"html",html:'<div class="layui-input-inline" style="width:82px;float:left;"><input type="text" name="icon" value="" id="menusIconPicker" lay-filter="menusIconPicker" autocomplete="off" class="layui-input"></div><div class="layui-input-block" style="margin-left:105px;margin-right:0;"><input type="text" name="name" value="" lay-verify="required" lay-reqtext="请输入菜单名称" placeholder="请输入菜单名称" autocomplete="off" class="layui-input"></div>',must:true},
                            {name:"url",title:"菜单标识",type:"text",value:'',placeholder:"请输入菜单标识"},
                            {name:"act",title:"权限路径",type:"textarea",value:'',placeholder:"多个以逗号隔开"},
                            {name:"link",title:"外链路径",type:"text",value:'',placeholder:"请输入外链路径(#全屏打开@全路由)"},
                            {name:"sort",title:"排序编号",type:"number",value:'100',verify:'required',placeholder:"请输入排序数字"},
                            {name:"is_menu",title:"是否菜单",type:"switch",value:'1'},
                            {name:"status",title:"菜单显示",type:"switch",value:'1'}
                        ]
                    });
                    form.val('menus_items_form',Dt);
                    /*图标选择*/
                    layui.iconPicker.render({
                        elem: '#menusIconPicker',
                        type: 'fontClass',
                        search: true,
                        page: false
                    });
                    /* 手动渲染字典:上级菜单 渲染下拉树 https://maplemei.gitee.io/xm-select/#/component/options */
                    var data = JSON.parse(JSON.stringify(menusTb.options.data));
                    if(Dt) Exitem(data,Dt.id,true);
                    admin.vDict(lay,{"MPARENTID":data});

                    form.on('submit(menus_items)',function(data){
                        var btn = $(this);
                        if (btn.attr('stop')){return false}else{btn.attr('stop',1)}
                        var field = data.field;
                        var post_url = field.id ? app_root+'edit' : app_root+'add';
                        field.is_menu = field.hasOwnProperty('is_menu') ? field.is_menu : '0';
                        field.status  = field.hasOwnProperty('status') ? field.status : '0';
                        admin.req(post_url,field,function(res){
                            layer.msg(res.msg,{shade:[0.4,'#000'],time:1500},function(){
                                if(res.code===1){
                                    layer.close(index);
                                    menusTb.refresh();

                                    let fold = layui.$('#menus-sz');
                                    if (fold.attr('data') === 1){
                                        console.log('click','data',fold.attr('data'))
                                        fold.trigger('click');
                                    }

                                }
                                btn.removeAttr('stop');
                            });
                        },'post',{headersToken:true});
                        return false;
                    });
                }
            });
        }

        /*本身和子类不可选为上级*/
        function Exitem(data, id, flag){
            for(var a in data){
                if(flag){
                    if(data[a].id === id){
                        data[a].disabled = true;
                        if(data[a].hasOwnProperty('children')) Exitem(data[a].children, id, false);
                    }else{
                        if(data[a].hasOwnProperty('children')) Exitem(data[a].children, id, flag);
                    }
                }else{
                    data[a].disabled = true;
                    if(data[a].hasOwnProperty('children')) Exitem(data[a].children, id, false);
                }
            }
        }

    });
</script>